<?php
namespace admin\action;

use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;

/**--tmpl-use--**/

use herosphp\core\Loader;

use message\service\TriggerNodeService;
use utils\sms\ProviderFactory;
use message\service\SmsService;

Loader::import('message.service.SmsService');

Loader::import('message.service.TriggerNodeService');
Loader::import('utils.sms.ProviderFactory');

class RemindAction extends CommonAction
{
    private $to_way = null;
    protected $serviceBean = "message.messageRemind.service";

    public function C_start()
    {
        parent::C_start();

        $remindModel = Loader::model('messageRemind');

        $this->to_way = $remindModel::TO_WAY_SITE_REMIND;
    }


    public function index(HttpRequest $request)
    {

        $remindService = Beans::get($this->serviceBean);

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page=$page;
        $this->pagesize=$pagesize;
        $export_arr = array();
        if( $request -> getParameter('export') == 1 ){
            $this->page=1;
            $this->pagesize=2147483648;
            $ids = $request -> getParameter('ids');
            if( is_array($ids) ){
                $str = "(0";
                foreach ($ids as $v) {
                    $str .= ",". $v;
                }
                $export_arr['id'] .= $str .")";
            }
        }
        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "select_mix_option2" => $request->getParameter('select_mix_option2'),
            "start_time" => $request->getParameter('start_time'),
            "end_time" => $request->getParameter('end_time'),
            "manager_name" => urldecode($request->getParameter('manager_name')),
            "to_way" => $this->to_way
        );


        $arr = $remindService->search($this -> pagesize, $this -> page, $search_arr+$export_arr);

        $items = $arr['items'];

        $itemsLen = count($items);

        for ($i = 0; $i < $itemsLen; $i++) {
            if ($items[$i]['manager_name'] == '') {

                $items[$i]['manager_name'] = 'system';
            }

        }

        if( $request -> getParameter('export') == 1 ){
            $excel = array();
            foreach ($items as $k => $v) {
                $tmp = array();
                $tmp[] = $v["member_username"];
                $tmp[] = $v["tmpl_name"];
                $tmp[] = $v["manager_name"];
                $tmp[] = $v["to_time"];
                $excel[] = $tmp;
            }
            $header = array('会员用户', '	模板名称', '发送人', '	发送时间');
            phpexcel("站内信列表", $header, $excel);
            exit();
        }

        $this->generatePageMenu($arr['total']);

        $this->assign('items', $items);
        $this->assign('search_arr', $search_arr);

        $this->assign("title", "站内信列表");
        $this->assign('bread', array('网站设置',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/index');


    }

    public function add(HttpRequest $request)
    {
        $remindService = Beans::get($this->serviceBean);

        $to_member_idoptions = Loader::model('member')->getItems(array('del_status'=>0));

        $option_arr = $remindService->getRemindTmpls($this->to_way);

        $this->assign('option_arr', $option_arr);
        $this->assign('to_member_idoptions', $to_member_idoptions);

        $this->assign("title", "添加站内信");
        $this->assign('bread', array('网站设置','站内信列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/remind/index'),'javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/add');

    }


    public function do_add(HttpRequest $request)
    {
        $remindService = Beans::get($this->serviceBean);
        $remindModel = Loader::model('messageRemind');

        $data = $request->getParameter('data');
        $item = $remindService->getRemindTmplById($data['tmpl_id']);
        $data['tmpl_name'] = $item['name'];
        $data['to_time'] = myNow();
        $data['to_way'] = $this->to_way;

        $remindModel->add($data) ? AjaxResult::ajaxSuccessResult() : AjaxResult::ajaxFailtureResult();

    }


    //根据id获取站内信
    public function getRemindById(HttpRequest $request)
    {

        $remindService = Beans::get($this->serviceBean);

        $item = $remindService->getRemindById($request->getParameter('id'));
        if($item['manager_name']==''){
            $item['manager_name']='System';
        }
        $item ? AjaxResult::ajaxResult('000', 'ok', $item) : AjaxResult::ajaxResult('001', 'no', $item);

    }


    //规则列表
    public function ruleIndex(HttpRequest $request)
    {

        $remindService = Beans::get($this->serviceBean);

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page=$page;
        $this->pagesize=$pagesize;
        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "select_mix_option2" => $request->getParameter('select_mix_option2'),
            "start_time" => $request->getParameter('start_time'),
            "end_time" => $request->getParameter('end_time'),
            "trigger_node" => $request->getParameter('trigger_node'),
            "status" => $request->getParameter('status'),
            "to_way" => $this->to_way

        );

        $arr = $remindService->searchByRule($pagesize, $page, $search_arr);

        $items = $arr['items'];

        $itemsLen = count($items);

        for ($i = 0; $i < $itemsLen; $i++) {

            $items[$i]['status'] = $remindService->getRemindRuleStatusText($items[$i]['status']);

            $items[$i]['trigger_node_text'] = $remindService->getRemindRuleTriggerNodeText($items[$i]['trigger_node']);
        }

        $rule_option_arr = $remindService->getRemindRuleTriggerNodeText();

        $this->assign('rule_option_arr', $rule_option_arr);

        $this->generatePageMenu($arr['total']);
        $this->assign('items', $items);
        $this->assign('search_arr', $search_arr);

        $this->assign("title", "规则列表");
        $this->assign('bread', array('网站设置',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/indexRule');
    }

    //添加规则
    public function ruleAdd(HttpRequest $request)
    {
        $remindService = Beans::get($this->serviceBean);

        $tmpl_option_arr = $remindService->getRemindTmpls($this->to_way);

        $rule_option_arr = $remindService->getRemindRuleTriggerNodeText();


        $this->assign('tmpl_option_arr', $tmpl_option_arr);
        $this->assign('rule_option_arr', $rule_option_arr);

        $this->assign("title", "添加规则");
        $this->assign('bread', array('网站设置','规则列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/remind/ruleIndex'),'javascript:;'));
        $this->setView('/remind/add_rule');


    }


    public function editRule(HttpRequest $request)
    {
        $remindService = Beans::get($this->serviceBean);

        $tmpl_option_arr = $remindService->getRemindTmpls($this->to_way);
        $rule_option_arr = $remindService->getRemindRuleTriggerNodeText();
        $statusList = $remindService->getRemindRuleStatusText();

        $item = Loader::model('messageRemindRule')->getItem(array('id' => $request->getParameter('id')));
        $tmplItem = $remindService->getRemindTmplById($item['tmpl_id']);
        $item['to_content'] = $tmplItem['content'];
        $this->assign("item", $item);
        $this->assign("statusList", $statusList);
        $this->assign("tmpl_option_arr", $tmpl_option_arr);
        $this->assign("rule_option_arr", $rule_option_arr);

        $this->assign("title", "编辑规则");
        $this->assign('bread', array('网站设置','规则列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/remind/ruleIndex'),'javascript:;'));
        $this->setView('/remind/edit_rule');

    }

    //添加规则
    public function do_addRule(HttpRequest $request)
    {
        $triggerNodeService = new TriggerNodeService();

        $data = $request->getParameter('data');

        if (!$triggerNodeService->validateTrggerNode($data['trigger_node'], $data['to_content'])) {

            AjaxResult::ajaxResult(1, '节点对应的模板里标签不匹配');
        }

        $data['addtime'] = myNow();
        $data['manager_id'] = adminId();
        $data['to_way'] = $this->to_way;

        $bool = Loader::model('messageRemindRule')->add($data);

        $bool ? AjaxResult::ajaxSuccessResult() : AjaxResult::ajaxFailtureResult();

    }

    //编辑规则
    public function do_editRule(HttpRequest $request)
    {

        $data = $request->getParameter('data');
        $id = $request->getParameter('id');

        $bool = Loader::model('messageRemindRule')->update($data, $id);

        $bool ? AjaxResult::ajaxSuccessResult() : AjaxResult::ajaxFailtureResult();
    }


    //模板列表
    public function tmplIndex(HttpRequest $request)
    {
        $remindService = Beans::get($this->serviceBean);

        $page = $request->getParameter('page');
        $pagesize = $request->getParameter('pagesize');

        if ($page <= 0) $page = 1;
        if ($pagesize <= 0) $pagesize = 15;
        $this->page=$page;
        $this->pagesize=$pagesize;

        $search_arr = array(
            "select_mix_option1" => $request->getParameter('select_mix_option1'),
            "select_mix_option_value1" => urldecode($request->getParameter('select_mix_option_value1')),
            "select_mix_option2" => $request->getParameter('select_mix_option2'),
            "start_time" => $request->getParameter('start_time'),
            "end_time" => $request->getParameter('end_time'),
            "status" => $request->getParameter('status'),
            "manager_name" => urldecode($request->getParameter('manager_name')),
            "to_way" => $this->to_way


        );
        $arr = $remindService->searchByTmpl($pagesize, $page, $search_arr);

        $items = $arr['items'];

        $itemsLen = count($items);

        for ($i = 0; $i < $itemsLen; $i++) {

            $items[$i]['status'] = $remindService->getRemindTmplStatusText($items[$i]['status']);

        }
        $this->generatePageMenu($arr['total']);

        $this->assign('items', $items);
        $this->assign('search_arr', $search_arr);

        $this->assign("title", "模板列表");
        $this->assign('bread', array('网站设置',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/indexTmpl');


    }

    //模板添加
    public function tmplAdd(HttpRequest $request)
    {

        $this->assign("title", "添加模板");
        $this->assign('bread', array('网站设置','模板列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/remind/tmplIndex'),'javascript:;'));
        $this->setView('/remind/add_tmpl');
    }

    public function editTmpl(HttpRequest $request)
    {
        $remindService = Beans::get($this->serviceBean);

        $item = Loader::model('messageRemindTmpl')->getItem(array('id' => $request->getParameter('id')));

        $statusList = $remindService->getRemindTmplStatusText();

        $this->assign("item", $item);
        $this->assign("statusList", $statusList);

        $this->assign("title", "编辑模板");
        $this->assign('bread', array('网站设置','模板列表',$this->getTemplateVar('title')));
        $this->assign('breadUrl', array('javascript:;',url('admin/remind/tmplIndex'),'javascript:;'));
        $this->setView('/remind/edit_tmpl');

    }

    //添加模板
    public function do_addTmpl(HttpRequest $request)
    {
        $data = $request->getParameter('data');
        $data['to_way'] = $this->to_way;
        $bool = Loader::model('messageRemindTmpl')->add($data);

        $bool ? AjaxResult::ajaxSuccessResult() : AjaxResult::ajaxFailtureResult();
    }

    //编辑模板
    public function do_editTmpl(HttpRequest $request)
    {
        $data = $request->getParameter('data');
        $id = $request->getParameter('id');

        if($data['status']==0&&Loader::model('messageRemindRule')->getItem(array('status'=>1,'tmpl_id'=>$id))){

            AjaxResult::ajaxResult('001','有规则在使用此模板，无法禁用');

        }

        $bool = Loader::model('messageRemindTmpl')->update($data, $id);

        $bool ? AjaxResult::ajaxSuccessResult() : AjaxResult::ajaxFailtureResult();

    }

    //获取模板信息
    public function getRemindTmplById(HttpRequest $request)
    {

        $remindService = Beans::get($this->serviceBean);

        $item = $remindService->getRemindTmplById($request->getParameter('id'));
        $item ? AjaxResult::ajaxResult('000', 'ok', $item) : AjaxResult::ajaxResult('001', 'no', $item);

    }

    //发送测试短信
    public function testSendSms(HttpRequest $request)
    {

        //$configs = $request->getParameter('configs');

        $user = $request->getParameter('accout');
        $pass = $request->getParameter('password');
        $sign = $request->getParameter('sign');
        $provider = $request->getParameter('provider');

        $content = $request->getParameter('test_content');
        $mobile = $request->getParameter('test_mobile');
        if($provider==''){
            AjaxResult::ajaxResult('001','短信服务商不能为空',null);
        }
        if($user==''){
            AjaxResult::ajaxResult('001','短信平台账号不能为空',null);
        }
        if($pass==''){
            AjaxResult::ajaxResult('001','短信平台密码不能为空',null);
        }
        if($content==''){
            AjaxResult::ajaxResult('001','短信内容不能为空',null);
        }
        if($mobile==''){
            AjaxResult::ajaxResult('001','手机号码不能为空',null);
        }
        if($sign==''){
            AjaxResult::ajaxResult('001','短信签名不能为空',null);
        }

        if(!isMobile($mobile)){
            AjaxResult::ajaxResult('001','手机号码格式不正确',null);
        }

        $smsService = new SmsService();
        $bool=$smsService->directSend($mobile,$content,$provider,$user,$pass,$sign);//发送短信

        $bool? AjaxResult::ajaxSuccessResult() : AjaxResult::ajaxFailtureResult();

    }

    public function testCommand()
    {

        $remindService = Beans::get($this->serviceBean);

        $remindService->commandBySmsRemind('会员注册成功规则',
            array("注册验证码"=>"1234"),
            'b21a582c2d22044eed9c7863','15011882783');//这里不要循环使用
        die;
        $memberArray = array(

            array(
                '会员注册成功规则',
                array(),
                'b21a582c2d22044eed9c7863'
            ),
            array(
                '修改会员账号验证码规则',
                array('验证码' =>'123456',),
                'b21a582c2d22044eed9c7863'
            ),
            array(
                '修改会员账号成功规则',
                array('新会员手机号' => '13580766394'),
                'b21a582c2d22044eed9c7863'
            ),
            array(
                '修改登录密码验证码规则',
                array('验证码' => '验证码'),
                'b21a582c2d22044eed9c7863'),
            array(
                '修改登录密码成功规则',
                array(),
                'b21a582c2d22044eed9c7863'
            ),
        );

        $tradingArray = array(

            array(
                '下单成功规则',
                array( '订单号' => 'DD16113000001000010', '截止付款时间' => '2016-12-30'),
                'b21a582c2d22044eed9c7863'
            ),
            array(
                '线上（大塑支付）规则',
                array( '订单号' =>'DD16113000001000010'),
                'b21a582c2d22044eed9c7863'),
            array(
                '线下（确认收款）规则',
                array( '订单号' => 'DD16113000001000010'),
                'b21a582c2d22044eed9c7863'),
            array(
                '发货成功（卖家配送）规则',
                array('订单号' => 'DD16113000001000010', '送货人姓名' => '小王', '送货人手机号码' => '1361664569'),
                'b21a582c2d22044eed9c7863'),
            array(
                '发货成功（买家自提）规则',
                array('订单号' => 'DD16113000001000010'),
                'b21a582c2d22044eed9c7863'),
            array(
                '收货成功规则',
                array( '订单号' => 'DD16113000001000010'),
                'b21a582c2d22044eed9c7863'
            ),

        );

        foreach (array_merge($memberArray,$tradingArray) as $k => $v) {

            $remindService->commandRemind($v[0], $v[1],$v[2]);//这里不要循环使用
            break;
        }

        die;
    }

}
